package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import entity.User;
import service.UserService;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login.ctl")
public class LoginCtrl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        String user_json= JSONUtil.getJSON(request);
        User userToLogin = JSON.parseObject(user_json, User.class);

        JSONObject message = new JSONObject();
        try{
            UserService.getInstance().login(userToLogin);
            if(userToLogin.getId()==null){
                message.put("msg","用户不存在/密码错误");
                message.put("code","500");

            }else {
                message.put("msg","操作成功");
                message.put("code","200");
            }
            response.getWriter().write(message.toJSONString());
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}
